//
//  UIImage+Ex.m
//  PgyHelper
//
//  Created by ex_liuzp9 on 2025/4/1.
//  Copyright © 2025 CleverPeng. All rights reserved.
//

#import "UIImage+Ex.h"
#import <CoreImage/CoreImage.h>

@implementation UIImage (Ex)

+ (UIImage *)generateQRCodeFromString:(NSString *)string size:(CGFloat)size {
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

    // 创建滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setValue:data forKey:@"inputMessage"];
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"]; // 容错级别 H 最高

    CIImage *qrCodeImage = filter.outputImage;

    // 放大二维码
    return [self resizeCIImage:qrCodeImage withSize:size];
}

// 放大 CIImage
+ (UIImage *)resizeCIImage:(CIImage *)image withSize:(CGFloat)size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));

    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpace, kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];

    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);

    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);

    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    CGColorSpaceRelease(colorSpace);

    UIImage *finalImage = [UIImage imageWithCGImage:scaledImage];
    CGImageRelease(scaledImage);

    return finalImage;
}

@end
